package demo.practice.leetcode;

import java.util.HashMap;
import java.util.Map;

public class Trie {

    class TrieeNode {
        boolean isend;
        Map<Character, TrieeNode> next;
        public TrieeNode() {
            this.isend=false;
            this.next= new HashMap<>();
        }
    }



    private TrieeNode root;

    /** Initialize your data structure here. */
    public Trie() {
        this.root= new TrieeNode();

    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieeNode current= this.root;
        for (int i=0;i<word.length();i++ ) {
            char c = word.charAt(i);
            if(current.next.get(c)==null ){
                current.next.put(c,new TrieeNode());
            }
            current= current.next.get(c);
        }
        current.isend=true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieeNode current= this.root;
        for (int i=0;i<word.length();i++){
            char c = word.charAt(i);
            if(current.next.get(c)==null)
                return false;
            current=current.next.get(c);
        }
        return  current.isend;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieeNode current= this.root;
        for (int i=0;i<prefix.length();i++){
            char c = prefix.charAt(i);
            if(current.next.get(c)==null)
                return false;
            current=current.next.get(c);
        }
        return  true;
    }







}
